<script setup lang="ts">
import { ArrowLeft, ArrowRight } from "@element-plus/icons-vue"
import { ElMessage } from "element-plus"
import { onMounted, ref } from "vue"
import { useRouter } from "vue-router"
import { useResumeStore } from "@/pinia/stores/resume"
import { useUserStore } from "@/pinia/stores/user"

// 路由和状态管理
const router = useRouter()
const resumeStore = useResumeStore()
const userStore = useUserStore()

// 进度控制状态 - 从store移到组件内
const currentStep = ref(0)
const steps = [
  { title: "基本信息" },
  { title: "实习经历" },
  { title: "技能特长" },
  { title: "语言能力" },
  { title: "获奖情况" },
  { title: "其他信息" }
]

// 步骤导航方法
function nextStep(): boolean {
  if (currentStep.value < steps.length - 1) {
    currentStep.value++
    return true
  }
  return false
}

function prevStep(): boolean {
  if (currentStep.value > 0) {
    currentStep.value--
    return true
  }
  return false
}

// 从store中解构需要的数据和方法
const { formData, addSkill, removeSkill, addInternExperience, removeInternExperience, addLanguage, removeLanguage, addAward, removeAward, initFormData, setCurrentUserId, generateResumePdf } = resumeStore

// PDF预览相关状态
const generatingPdf = ref(false)

// 提交表单
async function submitForm() {
  // 验证简历名称不能为空
  if (!formData.resumeName || formData.resumeName.trim() === "") {
    ElMessage.warning("简历名称不能为空")
    return
  }

  try {
    const success = await resumeStore.createResume()
    if (success) {
      ElMessage.success("简历创建成功！")
      // 直接跳转到简历列表页面，不需要延迟
      router.push("/internship/resume/list")
    }
  } catch (error) {
    ElMessage.error("创建失败，请重试")
    console.error("创建简历失败:", error)
  }
}

// 预览简历PDF
async function handlePreviewPdf() {
  try {
    generatingPdf.value = true

    // 直接调用store的generateResumePdf方法，内部会处理缓存逻辑
    const pdfResult = await generateResumePdf()

    if (pdfResult) {
      // 在新页面全屏打开PDF
      window.open(pdfResult, "_blank")
    }
  } catch (error) {
    ElMessage.error("PDF预览失败，请重试")
    console.error("PDF预览失败:", error)
  } finally {
    generatingPdf.value = false
  }
}

// 页面加载时初始化
onMounted(() => {
  // 初始化表单数据
  initFormData()

  // 确保设置当前用户ID
  if (userStore.userInfo?.userId) {
    setCurrentUserId(userStore.userInfo.userId)
  }
})
</script>

<template>
  <div class="add-resume-wrapper">
    <div class="resume-page">
      <div class="resume-banner">
        <div class="page-container">
          <h2 class="page-title">
            添加简历
          </h2>
        </div>
      </div>

      <div class="page-container">
        <div class="add-resume-container">
          <!-- 步骤条 -->
          <el-steps :current="currentStep" style="margin-bottom: 40px;">
            <el-step v-for="(step, index) in steps" :key="index" :title="step.title" />
          </el-steps>

          <!-- 表单区域 -->
          <el-card>
            <!-- 基本信息 -->
            <div v-show="currentStep === 0" class="form-section">
              <h3 class="section-title">
                基本信息
              </h3>
              <el-form label-width="120px">
                <el-form-item label="简历名称" required>
                  <el-input v-model="formData.resumeName" placeholder="请输入简历名称" maxlength="50" show-word-limit />
                </el-form-item>
                <el-form-item label="设为默认">
                  <el-switch v-model="formData.isDefault" active-value="1" inactive-value="0" />
                </el-form-item>
              </el-form>
            </div>

            <!-- 实习经历 -->
            <div v-show="currentStep === 1" class="form-section">
              <h3 class="section-title">
                实习经历
              </h3>
              <div v-for="(exp, index) in formData.internExperiences" :key="index" class="item-container">
                <div class="item-header">
                  <span>实习经历 {{ index + 1 }}</span>
                  <el-button
                    type="danger"
                    icon="Minus"
                    circle
                    size="small"
                    @click="removeInternExperience(index)"
                    :disabled="formData.internExperiences.length <= 1"
                  />
                </div>
                <el-form label-width="120px">
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="公司名称" required>
                        <el-input v-model="exp.company" placeholder="请输入公司名称" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="职位" required>
                        <el-input v-model="exp.position" placeholder="请输入实习职位" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="开始日期" required>
                        <el-date-picker
                          v-model="exp.startDate"
                          type="date"
                          placeholder="选择开始日期"
                          style="width: 100%;"
                          value-format="YYYY-MM-DD"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="结束日期">
                        <el-date-picker
                          v-model="exp.endDate"
                          type="date"
                          placeholder="选择结束日期"
                          style="width: 100%;"
                          value-format="YYYY-MM-DD"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-form-item label="工作内容" required>
                    <el-input v-model="exp.content" type="textarea" :rows="4" placeholder="请描述您的工作内容和职责" />
                  </el-form-item>
                </el-form>
              </div>
              <el-button type="primary" icon="Plus" @click="addInternExperience">
                添加实习经历
              </el-button>
            </div>

            <!-- 技能特长 -->
            <div v-show="currentStep === 2" class="form-section">
              <h3 class="section-title">
                技能特长
              </h3>
              <div v-for="(skill, index) in formData.skills" :key="index" class="item-container">
                <div class="item-header">
                  <span>技能 {{ index + 1 }}</span>
                  <el-button
                    type="danger"
                    icon="Minus"
                    circle
                    size="small"
                    @click="removeSkill(index)"
                    :disabled="formData.skills.length <= 1"
                  />
                </div>
                <el-form label-width="120px">
                  <el-form-item label="技能名称" required>
                    <el-input v-model="skill.skillName" placeholder="请输入技能名称" />
                  </el-form-item>
                  <el-form-item label="熟练程度">
                    <el-select v-model="skill.proficiency" placeholder="选择熟练程度">
                      <el-option label="初级" value="初级" />
                      <el-option label="中级" value="中级" />
                      <el-option label="高级" value="高级" />
                      <el-option label="精通" value="精通" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="描述">
                    <el-input v-model="skill.description" type="textarea" :rows="2" placeholder="请描述您的技能水平和应用经验" />
                  </el-form-item>
                </el-form>
              </div>
              <el-button type="primary" icon="Plus" @click="addSkill">
                添加技能
              </el-button>
            </div>

            <!-- 语言能力 -->
            <div v-show="currentStep === 3" class="form-section">
              <h3 class="section-title">
                语言能力
              </h3>
              <div v-for="(lang, index) in formData.languages" :key="index" class="item-container">
                <div class="item-header">
                  <span>语言 {{ index + 1 }}</span>
                  <el-button
                    type="danger"
                    icon="Minus"
                    circle
                    size="small"
                    @click="removeLanguage(index)"
                    :disabled="formData.languages.length <= 1"
                  />
                </div>
                <el-form label-width="120px">
                  <el-form-item label="语言" required>
                    <el-select v-model="lang.language" placeholder="选择语言">
                      <el-option label="英语" value="英语" />
                      <el-option label="日语" value="日语" />
                      <el-option label="法语" value="法语" />
                      <el-option label="德语" value="德语" />
                      <el-option label="西班牙语" value="西班牙语" />
                      <el-option label="其他" value="其他" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="水平">
                    <el-input v-model="lang.level" placeholder="例如：CET-4/CET-6/TEM-4/TEM-8" />
                  </el-form-item>
                  <el-form-item label="分数/等级">
                    <el-input v-model="lang.score" placeholder="例如：600分/优秀/良好" />
                  </el-form-item>
                </el-form>
              </div>
              <el-button type="primary" icon="Plus" @click="addLanguage">
                添加语言能力
              </el-button>
            </div>

            <!-- 获奖情况 -->
            <div v-show="currentStep === 4" class="form-section">
              <h3 class="section-title">
                获奖情况
              </h3>
              <div v-for="(award, index) in formData.awards" :key="index" class="item-container">
                <div class="item-header">
                  <span>奖项 {{ index + 1 }}</span>
                  <el-button
                    type="danger"
                    icon="Minus"
                    circle
                    size="small"
                    @click="removeAward(index)"
                    :disabled="formData.awards.length <= 1"
                  />
                </div>
                <el-form label-width="120px">
                  <el-form-item label="奖项名称" required>
                    <el-input v-model="award.name" placeholder="请输入奖项名称" />
                  </el-form-item>
                  <el-form-item label="颁发机构">
                    <el-input v-model="award.issuer" placeholder="请输入颁发机构" />
                  </el-form-item>
                  <el-form-item label="获得日期">
                    <el-date-picker
                      v-model="award.getDate"
                      type="date"
                      placeholder="选择获得日期"
                      style="width: 100%;"
                      value-format="YYYY-MM-DD"
                    />
                  </el-form-item>
                </el-form>
              </div>
              <el-button type="primary" icon="Plus" @click="addAward">
                添加获奖情况
              </el-button>
            </div>

            <!-- 其他信息 -->
            <div v-show="currentStep === 5" class="form-section">
              <h3 class="section-title">
                其他信息
              </h3>
              <el-form label-width="120px">
                <el-form-item label="其他补充">
                  <el-input
                    v-model="formData.otherInfo"
                    type="textarea"
                    :rows="6"
                    placeholder="请填写其他您认为重要的信息"
                    maxlength="500"
                    show-word-limit
                  />
                </el-form-item>
              </el-form>
            </div>
          </el-card>

          <!-- 按钮组 -->
          <div class="button-group">
            <el-button v-if="currentStep > 0" @click="prevStep()" class="mr-10">
              <ArrowLeft /> 上一步
            </el-button>
            <el-button
              v-if="currentStep < steps.length - 1"
              type="primary"
              @click="nextStep()"
              class="mr-10"
            >
              下一步 <ArrowRight />
            </el-button>
            <el-button
              v-if="currentStep === steps.length - 1"
              @click="handlePreviewPdf"
              :loading="generatingPdf"
              class="mr-10"
            >
              预览简历
            </el-button>
            <el-button
              v-if="currentStep === steps.length - 1"
              type="primary"
              @click="submitForm"
              class="mr-10"
            >
              提交
            </el-button>
            <el-button @click="router.push('/internship/resume/list')">
              取消
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.add-resume-wrapper {
  width: 100%;
  height: 100%;
}

.resume-page {
  background-color: #f7f8fa;
  min-height: calc(100vh - 64px);
}

.resume-banner {
  position: sticky;
  top: 0;
  z-index: 9;
  background: linear-gradient(90deg, #f0f6ff 0%, #f7fbff 100%);
  border-bottom: 1px solid #eef2f7;
}

.page-container {
  max-width: 1280px;
  margin: 0 auto;
  padding: 12px 16px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.add-resume-container {
  padding: 20px 0;

  .page-title {
    margin-bottom: 20px;
    font-size: 20px;
    font-weight: 500;
  }

  .form-section {
    .section-title {
      margin-bottom: 20px;
      font-size: 16px;
      color: #606266;
    }

    .item-container {
      background-color: #f9f9f9;
      padding: 15px;
      border-radius: 4px;
      margin-bottom: 20px;

      .item-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 1px solid #ebeef5;
        font-weight: 500;
      }
    }

    .el-button {
      margin-top: 10px;
    }
  }

  .button-group {
    margin-top: 30px;
    text-align: center;

    .mr-10 {
      margin-right: 10px;
    }
  }
}

// 响应式布局调整
@media (max-width: 768px) {
  .page-container {
    padding: 8px 12px;
  }

  .add-resume-container {
    padding: 15px 0;
  }
}
</style>
